/*
 * @Author: liuzehai
 * @Date: 2021-04-16 15:54:19
 * @LastEditTime: 2021-05-17 16:18:03
 * @LastEditors: liuzehai
 * @FilePath: /Card-to-payh5/src/plugins/axios.js
 * @Description: 由liuzehai创建！
 */
"use strict";

import axios from "axios";
import router from '@/router';
import { Dialog } from "vant";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: process.env.baseURL || process.env.VUE_APP_apiURL || "/"
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    let token = localStorage.getItem('token');
    // Do something before request is sent
    if (token) {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    if (response.status === 401 || response.status === 402) {
      localStorage.clear();
      sessionStorage.clear();
      // if (typeof window.cordova !== 'undefined') {
      //   router.push({ path: '/login' });
      // } else {
      //   aizhixin.callAppNative(
      //     JSON.stringify({
      //       type: "toLogin",
      //     })
      //   );
      // }
    } else {
      return response;
    }
  },
  function(error) {
    const res = error.response;
    // Do something with response error
    if (res.status === 401 || res.status === 402) {
      localStorage.clear();
      sessionStorage.clear();
      // if (typeof window.cordova !== 'undefined') {
      //   router.push({ path: '/login' });
      // } else {
      //   aizhixin.callAppNative(
      //     JSON.stringify({
      //       type: "toLogin",
      //     })
      //   );
      // }
    } else {
      Dialog.alert({
        message: `${res.data.msg}`,
        theme: 'round-button',
        confirmButtonColor: 'linear-gradient(to right, #ff6034, #ee1c25)',
      })
    }
    return Promise.reject(error);
  }
);

export default _axios;
